﻿using System;
using System.Reflection;
using System.Web;
using System.Web.SessionState;

namespace MyMVC
{
    public class ActionSupport
    {
        protected HttpRequest getRequest()
        {
            return HttpContext.Current.Request;
        }

        protected HttpResponse getResponse()
        {
            return HttpContext.Current.Response;
        }

        protected HttpSessionState getSession()
        {
            return HttpContext.Current.Session;
        }

        protected object getSession(string key)
        {
            return getSession()[key];
        }

        protected void setSession(string key, object obj)
        {
            getSession()[key] = obj;
        }

        protected string getParameter(string name)
        {
            return getRequest().Params[name];
        }

        protected string getIP()
        {
            string userIP;
            // HttpRequest Request = HttpContext.Current.Request;  
            HttpRequest Request = System.Web.HttpContext.Current.Request; // 如果使用代理，获取真实IP  
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                userIP = Request.ServerVariables["REMOTE_ADDR"];
            else
                userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (userIP == null || userIP == "")
                userIP = Request.UserHostAddress;
            if (userIP == "::1")
                return "172.0.0.1";
            return userIP;
        }

        protected T getPostData<T>()
        {
            T t = Activator.CreateInstance<T>();
            PropertyInfo[] fields = t.GetType().GetProperties();
            if (fields.Length > 0)
            {
                string str;
                foreach (PropertyInfo field in fields)
                {
                    str = getParameter(field.Name);
                    if (!string.IsNullOrEmpty(str))
                    {
                        //只支持Nullable
                        if (field.PropertyType.IsGenericType)
                            field.SetValue(t, Convert.ChangeType(str, Nullable.GetUnderlyingType(field.PropertyType)), null);
                        else
                            field.SetValue(t, Convert.ChangeType(str, field.PropertyType), null);
                    }
                }
            }
            return t;
        }
    }
}
